package cn.edu.scau.cmi.liangzaoqing.util;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.xml.bind.JAXBException;

import org.apache.metamodel.schema.Column;
import org.apache.metamodel.schema.Relationship;
import org.apache.metamodel.schema.Schema;
import org.apache.metamodel.schema.Table;

import cn.edu.scau.cmi.liangzaoqing.database.model.AllColumnsType;
import cn.edu.scau.cmi.liangzaoqing.database.model.ColumnType;
import cn.edu.scau.cmi.liangzaoqing.database.model.ColumnsType;
import cn.edu.scau.cmi.liangzaoqing.database.model.ForeignsType;
import cn.edu.scau.cmi.liangzaoqing.database.model.PhysicalPrimaryKeysType;
import cn.edu.scau.cmi.liangzaoqing.database.model.PrimaryKeysType;
import cn.edu.scau.cmi.liangzaoqing.database.model.Project;
import cn.edu.scau.cmi.liangzaoqing.database.model.ReferencedType;
import cn.edu.scau.cmi.liangzaoqing.database.model.ReferencedsType;
import cn.edu.scau.cmi.liangzaoqing.database.model.TableType;
import cn.edu.scau.cmi.liangzaoqing.domain.LeafNode;
import cn.edu.scau.cmi.liangzaoqing.domain.RootNode;

// 写数据库表的信息到XML文件
//将数据库的元数据写到XML文件里面，包括数据库里面的所有的表，每一个表的主键，物理主键，外键，引用列，剩余的列。
//该类的功能是填充schema里面各个table的具体信息，并不是真正把schema信息写入XML文件当中，将信息写入XML文件是通过调用javax.xml.bind.Marshaller里面的方法完成，可格式化输出文本！唐锦文20190301
public class DatabaseMetaDataOutputUtil {

	private String thisDataBaseType;
	private String thisIpAddress;
	private String thisPort;
	private String thisDataBaseScehma;
	private String thisUserName;
	private String thisPassword;
//	private Project project;

	public DatabaseMetaDataOutputUtil(String dataBaseType, String iPAddress, String port, String dataBaseScehma,
			String userName, String passWord) {
		super();
		thisDataBaseType = dataBaseType;
		thisIpAddress = iPAddress;
		thisPort = port;
		thisDataBaseScehma = dataBaseScehma;
		thisUserName = userName;
		thisPassword = passWord;
	}

	public List<TableType> getXmlTableSchema(Schema schema, List<TableType> XmlTableSchema, RootNode root)
			throws ClassNotFoundException, SQLException, JAXBException, IOException {
//		project = XmlToBeanUtil.getProject(physicalPKXmlFilePath);
		System.out.println("进入getXmlTableSchema方法");
		// 只有JDBC的数据库连接
		if (schema.getName().equals(this.thisDataBaseScehma)) {
			/* int index = 0; */
			Table[] tables = schema.getTables();
			Relationship[] relations = schema.getRelationships();
			/**
			 * 关于数据库Connection Statement ResultSet的关系：一个Connection可以有多个Statement，
			 * 一个Statement在任何时候只能有一个Active(活动的)的ResultSet，如果出现两个ResultSet，
			 * 则第二个ResultSet起作用时第一个ResultSet自动close。
			 */
			Class.forName("com.mysql.jdbc.Driver");
			Connection connection = DriverManager.getConnection(
					"jdbc:mysql://" + thisIpAddress + ":" + thisPort + "/" + schema.getName(), thisUserName,
					thisPassword);
			System.out.println("创建Connection过后");
			// ---------------------------------------------------------------
			for (int i = 0; i < tables.length; i++) {
				// 每一次读取表就新增加表
				System.out.println("------显示表名------" + tables[i].getName());
				Map<String, String> map = new HashMap<String, String>();

				map = getResultMap(connection, schema.getName(), tables[i].getName(), thisIpAddress, thisPort,
						thisUserName, thisPassword);
				System.out.println("map的内容：" + map.toString());

				TableType tabletype = new TableType();
				tabletype.setName((tables[i].getName()));

				if (!hasBasicColumn(tables[i]) && !hasReferencedColumn(relations, tables[i])) {
					tabletype.setIsRelation("true");
				} else
					tabletype.setIsRelation("false");

				XmlTableSchema.add(tabletype);
				/**
				 * 一个表需要添加key属性的列只有三种：主键/普通键/外键， 被引用键不需要添加，因为被引用键属于表本身的主键或者主键之一
				 */

				/*---------------------------------------------------------------------------------------------------*/
				System.out.println("开始添加所有列allColumns");
				// 开始添加allColumns
				Column[] allColumns = tables[i].getColumns();
				AllColumnsType allColumnsType = new AllColumnsType();
				tabletype.setAllColumnCount(allColumns.length);
				allColumnsType.setCount(allColumns.length);
				tabletype.setAllColumns(allColumnsType);
				for (int j = 0; j < allColumns.length; j++) {
					ColumnType column = new ColumnType();
					column.setName((allColumns[j].getName()));
					column.setJavaType(ColumnAttributeUtil.getJavaTypeOfColumn(allColumns[j].getNativeType()));
					column.setType(allColumns[j].getNativeType().toLowerCase());
					column.setKey(map.get(allColumns[j].getName()).toLowerCase());
					column.setOrder(j + 1 + "");
//					if (j == 0) {
//						column.setOrder("first");
//					} else if (j == allColumns.length - 1) {
//						column.setOrder("last");
//					} else {
//						column.setOrder(j + 1 + "");
//					}
					tabletype.getAllColumns().getColumn().add(column);
				}

				/*---------------------------------------------------------------------------------------------------*/
				System.out.println("开始添加主键primarykeys");
				// 添加主键primarykeys

				Column[] primaryColumns = tables[i].getPrimaryKeys();
				Column[] foreignKeys = tables[i].getForeignKeys();
				PrimaryKeysType primarykeys = new PrimaryKeysType();
				tabletype.setPrimaryKeyCount(primaryColumns.length);
				primarykeys.setCount(primaryColumns.length);
				tabletype.setPrimaryKeys(primarykeys);
				for (int j = 0; j < primaryColumns.length; j++) {
					boolean flag = false;
					ColumnType column = new ColumnType();
					column.setName((primaryColumns[j].getName()));
					column.setType(primaryColumns[j].getNativeType().toLowerCase());
					column.setJavaType(ColumnAttributeUtil.getJavaTypeOfColumn(primaryColumns[j].getNativeType()));
					column.setKey(map.get(primaryColumns[j].getName()).toLowerCase());
					column.setOrder(j + 1 + "");
//					if (j == 0) {
//						column.setOrder("first");
//					} else if (j == primaryColumns.length - 1) {
//						column.setOrder("last");
//					} else {
//						column.setOrder(j + 1 + "");
//					}
					if (!foreignKeys.equals(null)) {
						for (Column fcol : foreignKeys) {
							if (fcol.getName().equalsIgnoreCase(primaryColumns[j].getName())) {
								flag = true;
							}
						}
					}
					if (flag) {
						column.setIsForeignKey("true");
						column.setField(column.getName()+"Field");
					} else {
						column.setIsForeignKey("false");
						column.setField(column.getName());
					}
					tabletype.getPrimaryKeys().getColumn().add(column);
				}
				System.out.println("添加主键primarykeys过后");

				/*---------------------------------------------------------------------------------------------------*/
				// 添加物理主键physicalPrimarykeys
				System.out.println("开始添加物理主键primarykeys");
				
//				if (!isNewTable(project, tables[i].getName())) {
//					TableType responseTableType = getResponseTable(project, tables[i].getName());
//					tabletype.setPhysicalKCount(responseTableType.getPhysicalPrimaryKeys().getCount());
//					tabletype.setPhysicalPrimaryKeys(responseTableType.getPhysicalPrimaryKeys());
//				} else {
					PhysicalPrimaryKeysType physicalPrimaryKeys = new PhysicalPrimaryKeysType();
					List<LeafNode> physicalPrimaryColumns = root.getMiddleItems().get(i).getLeafItems();// 得到table的所有column，从中找出物理主键

					Iterator<LeafNode> physicalPrimaryColumnsIterator = physicalPrimaryColumns.iterator();

					while (physicalPrimaryColumnsIterator.hasNext()) {
						LeafNode physicalPrimary = physicalPrimaryColumnsIterator.next();
						if (physicalPrimary.isNull()) {
							// List集合删除元素要通过迭代器来实现,否则可能抛出错误
							physicalPrimaryColumnsIterator.remove();
						}
					}
					tabletype.setPhysicalPrimaryKeyCount(physicalPrimaryColumns.size());
					physicalPrimaryKeys.setCount(physicalPrimaryColumns.size());
					tabletype.setPhysicalPrimaryKeys(physicalPrimaryKeys);
					System.out.println("开始进行数据填充！！");

					for (int j = 0; j < physicalPrimaryColumns.size(); j++) {
						boolean flag = false;
						ColumnType column = new ColumnType();
						column.setName((physicalPrimaryColumns.get(j).getName()));
						column.setType(physicalPrimaryColumns.get(j).getType().toLowerCase());
						column.setJavaType(
								ColumnAttributeUtil.getJavaTypeOfColumn(physicalPrimaryColumns.get(j).getType()));
						column.setKey(map.get(physicalPrimaryColumns.get(j).getName()).toLowerCase());
						column.setOrder(j + 1 + "");
//						if (j == 0) {
//							column.setOrder("first");
//						} else if (j == physicalPrimaryColumns.size() - 1) {
//							column.setOrder("last");
//						} else {
//							column.setOrder(j + 1 + "");
//						}
						if (!foreignKeys.equals(null)) {
							for (Column fcol : foreignKeys) {
								if (fcol.getName().equalsIgnoreCase(physicalPrimaryColumns.get(j).getName())) {
									flag = true;
								}
							}
						}
						if (flag) {
							column.setIsForeignKey("true");
							column.setField(column.getName()+".id");
							column.setFieldUpper(column.getName()+"Id");
							column.setFieldGet(column.getName()+".getId()");
						} else {
							column.setIsForeignKey("false");
							column.setField(column.getName());
							column.setFieldUpper(column.getName());
							column.setFieldGet(tables[i].getName()+".get"+uppercaseFirst(column.getName())+"()");
						}

						tabletype.getPhysicalPrimaryKeys().getColumn().add(column);

					}
//				}

				System.out.println("添加物理主键physicalPrimarykeys过后");

				/*---------------------------------------------------------------------------------------------------*/
				// 添加非主键columns
				Column[] RestColumns = getBasicColumns(tables[i]);

				ColumnsType columns = new ColumnsType();
				tabletype.setBasicColumnCount(RestColumns.length);
				columns.setCount(RestColumns.length);
				tabletype.setBasicColumns(columns);
				for (int j = 0; j < RestColumns.length; j++) {
					ColumnType column = new ColumnType();
					column.setName((RestColumns[j].getName()));
					column.setType(RestColumns[j].getNativeType().toLowerCase());
					column.setJavaType(ColumnAttributeUtil.getJavaTypeOfColumn(RestColumns[j].getNativeType()));
					column.setKey(map.get(RestColumns[j].getName()).toLowerCase());
					column.setOrder(j + 1 + "");
//					if (j == 0) {
//						column.setOrder("first");
//					} else if (j == RestColumns.length - 1) {
//						column.setOrder("last");
//					} else {
//						column.setOrder(j + 1 + "");
//					}
					tabletype.getBasicColumns().getColumn().add(column);
				}
				System.out.println("添加非主键columns过后");

				/*---------------------------------------------------------------------------------------------------*/
				// 添加外键foreignkeys
				/*
				 * foreignTable is: student2teacher foreignColumns is: student primaryTable is:
				 * student primaryColumns is: id
				 */
				if (tables[i].getForeignKeys().equals(null)) {
					tabletype.setForeigns(null);
				} else {
					ForeignsType foreigns = new ForeignsType();
					tabletype.setForeignKeyCount(tables[i].getForeignKeys().length);
					foreigns.setCount(tables[i].getForeignKeys().length);
					tabletype.setForeigns(foreigns);
					int relationOrder = 0;
					for (int k = 0; k < relations.length; k++) {
						if (relations[k].getForeignTable().equals(tables[i])) {
							relationOrder++;
							boolean flag = false;
							/**
							 * 一个relation里面包含的外键与主键不是只有一个吗？ relation不是表之间的一条连接线吗？
							 */
							Column[] foreignColumns = relations[k].getForeignColumns();
							Column[] primaryColumn = relations[k].getPrimaryColumns();
							ColumnType column = new ColumnType();
							// 填写foreigns下面的column的 name
							for (int j = 0; j < foreignColumns.length; j++) {
								column.setName((foreignColumns[j].getName()));
								column.setType(foreignColumns[j].getNativeType().toLowerCase());
								column.setJavaType(
										ColumnAttributeUtil.getJavaTypeOfColumn(foreignColumns[j].getNativeType()));
								column.setKey(map.get(foreignColumns[j].getName()).toLowerCase());
								column.setOrder(relationOrder + "");
//								if (relationOrder == 1) {
//									column.setOrder("1");
//								} else if ((k == relations.length - 1)
//										|| !hasNextWantedRelation(relations, k, tables[i].getName(), false)) {
//									column.setOrder("last");
//								} else {
//									column.setOrder(relationOrder + "");
//								}
								if (!primaryColumns.equals(null)) {
									for (Column pcol : primaryColumns) {
										if (pcol.getName().equalsIgnoreCase(foreignColumns[j].getName())) {
											flag = true;
										}
									}
								}
								if (flag) {
									column.setIsPrimaryKey("true");
								} else {
									column.setIsPrimaryKey("false");
								}
							}
							// 纯联系表填充inverseJoinColumn和inverseJoinTable，其他表不需要
							if (tabletype.getIsRelation().equalsIgnoreCase("true")) {
								for (Column col : tables[i].getForeignKeys()) {
									if (!col.getName().equalsIgnoreCase(column.getName())) {
										column.setInverseJoinColumn((col.getName()));
										break;
									}
								}
								for (Relationship re : relations) {
									if (!re.equals(relations[k]) && re.getForeignTable().equals(tables[i])) {
										column.setInverseJoinTable((re.getPrimaryTable().getName()));
										break;
									}
								}
							}
							
							// 填写下面的referenceTable
							column.setReferenceTable((relations[k].getPrimaryTable().getName()));
							if (relations[k].getPrimaryTable().getName().equalsIgnoreCase(tables[i].getName())) {
								column.setIsReferenceSelf("true");
								if(column.getName().equalsIgnoreCase("parent")) {
									tabletype.setCompositeKey("parent");
								}
							} else {
								column.setIsReferenceSelf("false");
							}
							column.setReferenceCount(getReferenceCount(relations, 
									relations[k].getPrimaryTable().getName(),tables[i].getName()));
							// 如果本表通过外键多次引用另一表，则需要添加引用的顺序
							if (column.getReferenceCount() > 1) {
								column.setReferenceOrder("" + getReferenceOrder(tables[i],
										relations[k].getPrimaryTable().getName(), column.getName()));
							} else {
								column.setReferenceOrder("1");
							}
							// 填写下面的referenceColumn
							for (Column primarycolumn : primaryColumn) {
								column.setReferenceColumn((primarycolumn.getName()));
							}
							column.setHasReferenceLoop(
									hasReferenceLoop(relations[k].getForeignTable(), relations[k].getPrimaryTable()));
							tabletype.getForeigns().getColumn().add(column);
						}
					}
				}
				System.out.println("添加外键foreignkeys过后");

				/*---------------------------------------------------------------------------------------------------*/
				// 往里面添加被引用的情况referenced tables and column
				ReferencedsType Referenceds = new ReferencedsType();

				int count = 0;
				for (Relationship relation : relations) {
					if (relation.getPrimaryTable().equals(tables[i])) {
						count++;
					}
				}
				tabletype.setReferencedCount(count);
				Referenceds.setCount(count);
				tabletype.setReferenceds(Referenceds);
				int relationshipOrder = 0;
				for (int k = 0; k < relations.length; k++) {
					if (relations[k].getPrimaryTable().equals(tables[i])) {
						relationshipOrder++;
						ReferencedType reference = new ReferencedType();
						String foreignTableName = relations[k].getForeignTable().getName();
						reference.setName((foreignTableName));

						if (hasBasicColumn(relations[k].getForeignTable())
								|| hasReferencedColumn(relations, relations[k].getForeignTable())) {
							reference.setIsRelation("false");
						} else
							reference.setIsRelation("true");
						reference.setReferenceCount(getReferenceCount(relations,relations[k].getForeignTable().getName(),relations[k].getPrimaryTable().getName())+"");
						ColumnType column = new ColumnType();
						Column[] priColumns = relations[k].getPrimaryColumns();
						Column[] foreignColumns = relations[k].getForeignColumns();

						for (Column primarycolumn : priColumns) {
							column.setReferencedColumn((primarycolumn.getName()));
						}

						column.setReferencedCount(getReferenceCount(relations, relations[k].getPrimaryTable().getName(),relations[k].getForeignTable().getName()));

						Map<String, String> foreignTableMap = new HashMap<>();

						foreignTableMap = getResultMap(connection, schema.getName(), foreignTableName, thisIpAddress,
								thisPort, thisUserName, thisPassword);

						System.out.println("::打印被引用列的key值::");
						for (int j = 0; j < foreignColumns.length; j++) {
							column.setName((foreignColumns[j].getName()));
							column.setType(foreignColumns[j].getNativeType().toLowerCase());
							column.setJavaType(
									ColumnAttributeUtil.getJavaTypeOfColumn(foreignColumns[j].getNativeType()));
							column.setKey(foreignTableMap.get(foreignColumns[j].getName()).toLowerCase());
							// 设置该列在该类型列所有列里的相对位置
							column.setOrder(relationshipOrder + "");
//							if (relationshipOrder == 1) {
//								column.setOrder("first");
//							} else if ((k == relations.length - 1)
//									|| !hasNextWantedRelation(relations, k, tables[i].getName(), true)) {
//								column.setOrder("last");
//							} else {
//								column.setOrder(relationshipOrder + "");
//							}
							// 设置该列在纯联系表所有外键列里的相对位置
							if (reference.getIsRelation() == "true") {
								column.setColumnOrder(getColumnIndex(relations[k].getForeignTable().getForeignKeys(),
										column.getName()) + "");
							}

							Column[] allKeys = relations[k].getForeignTable().getForeignKeys();
							Column[] keys = relations[k].getForeignColumns();
							if (reference.getIsRelation().equalsIgnoreCase("false")) {
								column.setInverseJoinColumn("none");
								column.setInverseJoinTable("none");
							} else {
								// 有局限性，只适合只有两个外键的纯联系表。其他联系表不适合这个方法。
								for (Column foreignKey : allKeys) {
									boolean flag = false;
									for (Column key : keys) {
										if (foreignKey.getName().equalsIgnoreCase(key.getName())) {
											flag = true;
										}
									}
									if (!flag) {
										column.setInverseJoinColumn((foreignKey.getName()));
										break;
									}
								}
								Relationship[] ralations4Table = relations[k].getForeignTable().getRelationships();
								for (Relationship re : ralations4Table) {
									if (!re.getPrimaryTable().getName().equalsIgnoreCase(tables[i].getName())) {
										column.setInverseJoinTable((re.getPrimaryTable().getName()));
									}
								}
							}
							column.setHasReferenceLoop(
									hasReferenceLoop(relations[k].getForeignTable(), relations[k].getPrimaryTable()));
							// 如果其他表通过外键多次引用本表，则需要添加引用的顺序
							if (column.getReferencedCount() > 1) {
								column.setReferencedOrder("" + getReferenceOrder(relations[k].getForeignTable(),
										tables[i].getName(), column.getName()));
							} else {
								column.setReferencedOrder("1");
							}
						}
						reference.setColumn(column);
						tabletype.getReferenceds().getReferencedTable().add(reference);
					}
				}

				System.out.println("添加被引用键referenced过后");
			}
		}
		System.out.println("OK!");
		return XmlTableSchema;
	}

	public boolean isNewTable(Project project, String searchTableName) {
		for (TableType table : project.getModel().getDatabase().getTables().getTable()) {
			if (table.getName().equalsIgnoreCase(searchTableName)) {
				return false;
			}
		}
		return true;
	}

	public TableType getResponseTable(Project project, String searchTableName) {
		for (TableType table : project.getModel().getDatabase().getTables().getTable()) {
			if (table.getName().equalsIgnoreCase(searchTableName)) {
				return table;
			}
		}
		return null;
	}

	public int getColumnIndex(Column[] foreignColumns, String columnName) {
		if (foreignColumns.length != 0) {
			int i = 0;
			for (i = 0; i < foreignColumns.length; i++) {
				if (!foreignColumns[i].getName().equalsIgnoreCase(columnName)) {
					i++;
				} else {
					i++;
					break;
				}
			}
			return i;
		} else
			return 0;
	}

	public String hasReferenceLoop(Table foreirnTable, Table primaryTable) {
		int flag = 0;
		for (Relationship re : foreirnTable.getForeignKeyRelationships()) {
			if (re.getPrimaryTable().getName().equalsIgnoreCase(primaryTable.getName())) {
				flag++;
				break;
			}
		}
		for (Relationship re : primaryTable.getForeignKeyRelationships()) {
			if (re.getForeignTable().getName().equalsIgnoreCase(foreirnTable.getName())) {
				flag++;
				break;
			}
		}
		return flag == 2 ? "true" : "false";
	}

	public int getReferenceOrder(Table foreignTable, String primaryTableName, String columnName) {
		ArrayList<Column> columns = new ArrayList<>();
		// 找出所有符合条件的Column
		for (Relationship re : foreignTable.getForeignKeyRelationships()) {
			if (re.getPrimaryTable().getName().equalsIgnoreCase(primaryTableName)) {
				columns.add(re.getForeignColumns()[0]);
			}
		}

		if (columns.size() != 0) {
			int i = 0;
			for (i = 0; i < columns.size(); i++) {
				if (!columns.get(i).getName().equalsIgnoreCase(columnName)) {
					i++;
				} else {
					i++;
					break;
				}
			}
			return i;
		} else
			return 0;
	}

	public boolean hasNextWantedRelation(Relationship[] relations, int currentIndex, String tableName,
			boolean isPrimaryTable) {

		if (isPrimaryTable) {
			for (int k = currentIndex + 1; k < relations.length; k++) {
				if (relations[k].getPrimaryTable().getName() == tableName) {
					return true;
				}
			}
			return false;
		} else {
			for (int k = currentIndex + 1; k < relations.length; k++) {
				if (relations[k].getForeignTable().getName() == tableName) {
					return true;
				}
			}
			return false;
		}
	}

	public Integer getReferenceCount(Relationship[] relations, String referencedTableName, String referenceTableName) {
		int count = 0;
		for (Relationship relation : relations) {
			if (relation.getForeignTable().getName() == referenceTableName
					&& relation.getPrimaryTable().getName() == referencedTableName) {
				count++;
			}
		}
		return count;
	}

	public boolean hasReferencedColumn(Relationship[] relations, Table table) {
		for (Relationship relation : relations) {
			if (relation.getPrimaryTable().getName().equals(table.getName())) {
				return true;
			}
		}
		return false;
	}

	public boolean hasBasicColumn(Table table) {
		Column[] basicColumns = getBasicColumns(table);
		return basicColumns.length == 0 ? false : true;
	}

	public static String camelCase(String str) {
		String strings[];
		if (str.contains("_")) {
			strings = str.toLowerCase().trim().split("_| ");
		} else {
			strings = str.trim().split("_| ");
		}
		StringBuilder builder = new StringBuilder();
		for (String string : strings) {
			if (string.length() > 0) {
				builder.append(string.replaceFirst(string.substring(0, 1), string.substring(0, 1).toUpperCase()));
			}
		}
		return new String(builder);
	}

	public static String lowercaseFirst(String sourceString) {
		char c[] = sourceString.toCharArray();
		c[0] = Character.toLowerCase(c[0]);
		sourceString = new String(c);
		return sourceString;
	}
	
	public static String uppercaseFirst(String sourceString) {
		char c[] = sourceString.toCharArray();
		c[0] = Character.toUpperCase(c[0]);
		sourceString = new String(c);
		return sourceString;
	}

	public Map<String, String> getResultMap(Connection connection, String schemaName, String tableName,
			String ipAddress, String port, String userName, String password)
			throws SQLException, ClassNotFoundException {
		Map<String,String> keyMap = new HashMap<>();
		keyMap.put("UNI", "unique");
		keyMap.put("MUL", "multi");
		keyMap.put("PRI", "primary");
		Statement stmt = connection.createStatement();

		System.out.println("执行Query之前");

		String query = "DESC " + tableName;
		System.out.println(""+query);

		ResultSet resultSet = stmt.executeQuery(query);
		System.out.println("执行Query之后");

		System.out.println("：：：：foreignTableResultSet的内容：：：：" + resultSet.toString());

		Map<String, String> columnKeyMap = new HashMap<>();
		System.out.println("填充map之前");

		while (resultSet.next()) {
			if (resultSet.getString(4) == "") {
				columnKeyMap.put((resultSet.getString(1)), "none");
				System.out.println(resultSet.getString(1)+":"+"none");
			}	
			else {
				columnKeyMap.put((resultSet.getString(1)), keyMap.get(resultSet.getString(4)));
				System.out.println(resultSet.getString(1)+":"+resultSet.getString(4));
			}
		}
		System.out.println("填充columnKeyMap之后");
		
	    System.out.println("columnKeyMap==>>"+columnKeyMap);
		return columnKeyMap;
	}

	public Column[] getBasicColumns(Table table) {
		// System.out.println("显示表名----" + table.getName());
		Column[] columns = table.getColumns();// 获得所有列
		Column[] foreignColumns = table.getForeignKeys();// 获得充当外键的列
		ArrayList<Column> restColumn = new ArrayList<Column>();
		// ---------------------------------------
		for (Column column : columns) {
			int flag = 0;
			if (!column.isPrimaryKey()) {
				// System.out.println(column.getName());
				if (foreignColumns.length == 0) {
					restColumn.add(column);
					flag = 1;

				} else {
					for (Column foreignKey : foreignColumns) {
						if (column.getName().equals(foreignKey.getName())) {
							flag = 1;
							break;
						}
					}
				}
				if (flag == 0) {
					restColumn.add(column);
				}
			}
		}
		
		int length = restColumn.size();
		Column[] rest = new Column[length];
		for (int i = 0; i < length; i++) {
			rest[i] = restColumn.get(i);
		}
		return rest;
	}
}
